package hu.webdream.android.contacts;

import android.app.ListActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {

	private ContactDAO contactDao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.contactDao = new ContactDAO(this);
		this.setListAdapter(new ListAdapter<Contact>(this, this.contactDao
				.getAll()));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		this.getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void newContact(MenuItem item) {
		Intent intent = new Intent(this, NewContactActivity.class);
		this.startActivity(intent);
	}

	public void loadDemoData(MenuItem item) {
		SQLiteDatabase db = new ContactDbHelper(this.getApplicationContext())
				.getWritableDatabase();

		if (db != null) {
			Toast.makeText(MainActivity.this, "Database is created!",
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(MainActivity.this, "Error creating database!",
					Toast.LENGTH_SHORT).show();
			new ContactDbHelper(this.getApplicationContext()).loadDemoData(db);
		}
	}

	@Override
	protected void onListItemClick(ListView listView, View view, int position,
			long id) {
		// Item that was clicked
		Contact contact = (Contact) this.getListAdapter().getItem(position);

		// Delete object from the database
		this.contactDao.deleteContact(contact.getId());

		// Set the list adapter and get list via DAO
		this.setListAdapter(new ListAdapter<Contact>(this, this.contactDao
				.getAll()));

		// Display success information
		Toast.makeText(this.getApplicationContext(), "Deleted!",
				Toast.LENGTH_LONG).show();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		// Create an intent
		Intent intent = new Intent(this, NewContactActivity.class);
		// Start activity
		this.startActivity(intent);
		// Finish this activity
		this.finish();

		// Close the database
		this.contactDao.close();

		return super.onOptionsItemSelected(item);
	}
}
